//
//  ViewController.m
//  随机排序——OC
//
//  Created by Mac on 2019/8/7.
//  Copyright © 2019 Mac. All rights reserved.
//

#import "ViewController.h"
#import <mach/mach_time.h>

@interface ViewController ()

@end

@implementation ViewController
- (IBAction)paixu:(id)sender {
    NSArray *arry=@[@"上海",@"北京",@"天津",@"重庆",@"香港",@"台湾",@"澳门"];
    CFAbsoluteTime start =CFAbsoluteTimeGetCurrent();
    
    NSLog(@"%@",[self randamArry:arry]);
    CFAbsoluteTime end =  CFAbsoluteTimeGetCurrent();
    
    NSLog(@"%f", end - start);


}
- (IBAction)paixu2:(UIButton *)sender {
    NSArray *arry=@[@"上海",@"北京",@"天津",@"重庆",@"香港",@"台湾",@"澳门"];
    
    CFAbsoluteTime start =CFAbsoluteTimeGetCurrent();
    
    NSLog(@"%@",[self getRandomArrFrome:arry]);
    
    CFAbsoluteTime end =  CFAbsoluteTimeGetCurrent();
    
    NSLog(@"%f", end - start);
  
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *arry=@[@"上海",@"北京",@"天津",@"重庆",@"香港",@"台湾",@"澳门"];
    [self randamArry:arry];
   

}

- (NSArray *)randamArry:(NSArray *)arry
{
    // 对数组乱序
    arry = [arry sortedArrayUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
        int seed = arc4random_uniform(2);
        
        if (seed) {
            return [str1 compare:str2];
        } else {
            return [str2 compare:str1];
        }
    }];
    return arry;
    
}

-(NSMutableArray*)getRandomArrFrome:(NSArray*)arr
{
    NSMutableArray *newArr = [NSMutableArray new];
    while (newArr.count != arr.count) {
        //生成随机数
        int x =arc4random() % arr.count;
        id obj = arr[x];
        if (![newArr containsObject:obj]) {
            [newArr addObject:obj];
        }
    }
    return newArr;
}



@end
